package com.fly.simple.service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.SystemUtils;

import com.fly.simple.entity.Article;
import com.fly.simple.entity.BlogData;
import com.fly.simple.entity.Record;
import com.fly.simple.utils.JsonBeanUtils;
import com.fly.simple.utils.ShellExecutor;

import lombok.extern.slf4j.Slf4j;

/**
 * JsonData服务类
 */
@Slf4j
public class JsonDataService
{
    private static File outFile = new File(ResourceBundle.getBundle("config").getString("out"));
    
    public static void parseDir(File directory)
    {
        try
        {
            // 遍历目录下json文件
            Collection<File> files = FileUtils.listFiles(directory, new String[] {"json"}, false);
            List<Article> articles = files.stream().map(f -> parseToArticles(f)).flatMap(List::stream).distinct().collect(Collectors.toList());
            log.info("articles length : {}", articles.size());
            
            // 构造对象，写入结果文件
            BlogData blogData = new BlogData().setData(new Record().setList(articles));
            FileUtils.writeStringToFile(outFile, JsonBeanUtils.beanToJson(blogData, true), StandardCharsets.UTF_8, false);
            if (SystemUtils.IS_OS_WINDOWS)
            {
                ShellExecutor.exec("start " + outFile.getParent());
            }
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 解析File为List
     * 
     * @param resource
     * @return
     */
    private static List<Article> parseToArticles(File file)
    {
        try
        {
            String jsonData = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
            return JsonBeanUtils.jsonToBean(jsonData, BlogData.class, true).getData().getList();
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}